# coding=utf-8

from PIL import Image, ImageDraw, ImageFont, ImageColor

from app.langconv import *
# https://github.com/skydark/nstools/tree/master/zhtools

# 转换繁体到简体
def cht_to_chs(line):
    line = Converter('zh-hans').convert(line)
    line.encode('utf-8')
    return line

# 转换简体到繁体
def chs_to_cht(line):
    line = Converter('zh-hant').convert(line)
    line.encode('utf-8')
    return line

def genorate_image(str1):
    # 获取文本
    scentences = chs_to_cht(str1).split()
    scentences_count = len(scentences)

    # 创建Font对象:
    font = ImageFont.truetype('app/images/font.TTF', 72)

    # 打开底版图片
    imageFile = 'app/images/bg.jpg'
    im1=Image.open(imageFile)

    # 在图片上添加文字
    draw = ImageDraw.Draw(im1)
    x_offset, y_offset = 120, 100
    i,j = 0, 0
    for scentence in scentences:
        j = 0
        for word in scentence:
            x = 780 - x_offset * i
            y = 180 + y_offset * j
            draw.text((x,y),word,(152,4,4),font = font)
            j += 1
        i += 1
    draw = ImageDraw.Draw(im1)
    '''
    # 在图片上添加另一张图片（分割线、logo）
    imageFile = 'images/logo.png'
    im2=Image.open(imageFile)
    box = (0, 0, 68, 78)
    im2_logo = im2.crop(box)

    im1.paste(im2_logo,(120,1300,120+68,1300+78))
    '''
    # 保存
    im1.save('app/static/target.jpg', 'jpeg')

def genorate_image(str1,font_path='app/images/font_fangzheng.TTF',size=36,font_color_name='black',bg_path='app/images/bg.jpg',direction='horizontal'):
    # 获取文本
    scentences = chs_to_cht(str1).split()
    scentences_count = len(scentences)

    # 创建Font对象:
    font = ImageFont.truetype(font_path, size)
    font_color = ImageColor.getrgb(font_color_name)
    # 打开底版图片
    imageFile = bg_path
    im1=Image.open(imageFile)
    draw = ImageDraw.Draw(im1)

    # 在图片上添加文字
    if direction == 'horizontal':
        empty_line = size
        indent_space = size
        x_offset, y_offset = size*1.5, size*1.5
        i, j = 0, 0

        for scentence in scentences:
            j = 0
            for word in scentence:
                x = x_offset * j + indent_space * 4
                y = y_offset * i + empty_line * 2
                draw.text((x, y), word, font_color, font=font)
                j += 1
            i += 1
    else:
        x_offset, y_offset = 120, 100
        i, j = 0, 0
        for scentence in scentences:
            j = 0
            for word in scentence:
                x = 780 - x_offset * i
                y = 180 + y_offset * j
                draw.text((x, y), word, font_color, font=font)
                j += 1
            i += 1

    draw = ImageDraw.Draw(im1)

    # 保存
    im1.save('app/static/target.jpg', 'jpeg')